package com.zc.im.register.config;

import com.zc.im.common.constant.RegisterInfoConstant;
import com.zc.im.register.cache.RegisterCache;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.CuratorCache;
import org.apache.curator.framework.recipes.cache.CuratorCacheListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.stream.Collectors;

/**
 * Project：im
 * Date：2022-04-23
 * Time：17:19
 * Description：zk配置类
 *
 * @author ChallenZhang
 * @version 1.0
 */
@Component
public class ZkConfig {

    @Autowired
    private RegisterCache registerCache;

    @Bean
    public CuratorCache curatorCache(CuratorFramework curatorClient) {
        CuratorCache curatorCache = CuratorCache.build(curatorClient, RegisterInfoConstant.REGISTER_PATH);
        CuratorCacheListener build = CuratorCacheListener.builder()
                .forInitialized(() -> {
                    registerCache.refresh(curatorCache);
                }).forAll((type, oldData, newData) -> {
                    registerCache.refresh(curatorCache);
                }).build();
        curatorCache.listenable().addListener(build);
        curatorCache.start();
        return curatorCache;
    }

    @PreDestroy
    public void destroy(CuratorCache curatorCache) {
        curatorCache.close();
    }
}
